package com.sparrow.core.arithmetic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;

public class Combination {
	private List<String> result = new ArrayList<String>();

	/**
	 * @author zlz
	 * 
	 * @time 2013-5-7下午1:43:20
	 * @param args
	 */
	public static void main(String[] args) {
		Combination c = new Combination();
		List<String> list = c.execute("12,2424,234234".split("\\,"));
		for (String item : list) {
			System.out.println(item);
		}
		System.out.println(list.size());
	}

	/**
	 * @author zlz
	 * 
	 * @time 2013-5-7下午3:29:57
	 * @param selectingArray
	 *            备选
	 * @param seed
	 *            种子
	 */
	public void matche(Stack<String> selectingArray, String seed) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < selectingArray.size(); i++) {
			// 第一个元素是种子已经加入到组合元素中
			if (i == 0) {
				sb.append(seed);
			}
			sb.append(",");
			sb.append(selectingArray.get(i));
			// 将每一个组合加入组合元素中
			this.result.add(sb.toString());
		}
		// 将备选元素移除一个
		if (selectingArray.size() > 0) {
			selectingArray.remove(0);
		}
		// 移除后还存在则继续寻找
		if (selectingArray.size() > 0) {
			this.matche(selectingArray, seed);
		}
	}

	public List<String> execute(Object[] array) {
		// 种子堆栈
		Stack<String> seedStack = new Stack<String>();
		// 将数组所有元素入栈
		for (int i = array.length - 1; i >= 0; i--) {
			seedStack.push(array[i].toString());
		}
		// 种子栈为空
		while (!seedStack.isEmpty()) {
			// 选出一个种子
			String seed = seedStack.pop();
			// 将其余元素做为种子的配对元素
			Stack<String> selectingStack = new Stack<String>();
			for (int i = seedStack.size() - 1; i >= 0; i--) {
				selectingStack.push(seedStack.get(i));
			}
			// 将种子做为组合的第一个元素
			// this.result.add(seed);
			// 将当前种子与其他元素配对
			this.matche(selectingStack, seed);
		}

		Collections.sort(this.result, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return o2.length() - o1.length();
			}
		});

		return this.result;
	}
}
